package com.lh.ssm.web;

import com.lh.ssm.domain.User;
import com.lh.ssm.service.UserService;
import com.lh.ssm.util.Constants;
import com.lh.ssm.util.RandomUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.jar.JarOutputStream;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    //localhost:8080/user?username=2&method=check
    //localhost:8080/user/check?username=2&method=check

    @ResponseBody()
    @RequestMapping("/check")
    public String check(String username){

        User result = userService.checkUsername(username);

        if(result != null){
            return "1";
        }else{
            return "0";
        }

    }


    @PostMapping("/register")
    public String register(User user, HttpServletRequest req){

        //设置默认状态,未激活状态
        user.setState(Integer.valueOf(Constants.USER_NOT_ACTIVE));
        user.setRole(Constants.ROLE_CUSTOMER);
        user.setCode(RandomUtils.getActiveCode());
        System.out.println(user);
        int result = userService.register(user);

        //跳转到注册失败页面
        if (result <= 0) {
            req.setAttribute("registerMsg", "注册失败");
            return "register";
        }
        //跳转到注册成功页面
        return "registerSuccess";

    }


    @GetMapping("/active")
    public String active(String c,HttpServletRequest request){
        if(userService.active(c)==1){
            request.setAttribute("msg","激活成功！");
            return "message";
        }else{
            request.setAttribute("msg","激活失败！");
            return "message";
        }

    }

    @PostMapping("/login")
    public String login(String username,String password,String code,String auto,HttpServletRequest request,HttpServletResponse response){
        //获取前端生成的验证码
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute("captcha");

        //1、获取请求参数，校验验证码
        if (code == null || !code.equalsIgnoreCase(sessionCode)) {
            System.out.println("1..");
            request.setAttribute("msg", "验证码错误");
            return "login";
        }
        //2、查询是否存在该用户
        User user = userService.login(username,password);
       // System.out.println(user);
        if (user == null) {
            request.setAttribute("msg", "用户名或密码错误");
            System.out.println("2..");
            return "login";
        }

        if (user.getState() == (Integer.parseInt(Constants.USER_NOT_ACTIVE))) {//?是否可以将int和string一起作比较
            request.setAttribute("msg", "账号未激活,请先去激活...");
            System.out.println("3..");
            return "login";
        }

        //存储了用户的登录状态  (？？？)
        session.setAttribute("loginUser",user);

        //4.判断用户是否勾选了"自动登录"?
        if (auto == null) {
            Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        } else {
            //username:password
            String content = username + Constants.FLAG + password;
            Cookie cookie = new Cookie(Constants.AUTO_NAME,content);
            cookie.setPath("/");
            cookie.setMaxAge(14 * 24 * 60 * 60);
            response.addCookie(cookie);
        }

        return "index";
    }

    /**
     * 退出登录（？？？）
     */
    @RequestMapping("/logOut")
    public String logOut(HttpServletRequest req, HttpServletResponse resp) {
        //清除session信息
        HttpSession session = req.getSession();
        session.removeAttribute("loginUser");

        //清除cookie
        Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        resp.addCookie(cookie);

        //req.setAttribute("msg", "退出成功");

        return "login";
    }
}
